import { dataLoaderService, LoadPriority } from './dataLoaderService'
import { renderOptimizationService } from './renderOptimizationService'
import { memoryManagementService } from './memoryManagementService'
import { logDataCache, dumpPathCache, componentCache } from '../utils/cacheManager'
// import { useWorkspaceStore } from '../stores/workspace'
import { useDumpStore } from '../stores/dumps'

// 性能指标接口
export interface PerformanceMetrics {
  pageLoadTime: number
  firstContentfulPaint: number
  largestContentfulPaint: number
  cumulativeLayoutShift: number
  firstInputDelay: number
  memoryUsage: number
  cacheHitRate: number
  renderTime: number
}

// 优化配置
export interface OptimizationConfig {
  enableCaching: boolean
  enableVirtualization: boolean
  enableLazyLoading: boolean
  enableMemoryManagement: boolean
  enablePreloading: boolean
  cachePrewarmingEnabled: boolean
  maxCacheSize: number
  memoryThresholds: {
    warning: number
    critical: number
    maximum: number
  }
}

// 优化状态
export interface OptimizationStatus {
  isInitialized: boolean
  isOptimizing: boolean
  lastOptimizationTime: number
  optimizationCount: number
  errors: string[]
}

/**
 * 性能优化主服务
 * 统一管理所有性能优化功能
 */
export class PerformanceOptimizationService {
  private config: OptimizationConfig = {
    enableCaching: true,
    enableVirtualization: true,
    enableLazyLoading: true,
    enableMemoryManagement: true,
    enablePreloading: true,
    cachePrewarmingEnabled: true,
    maxCacheSize: 1024, // 1GB
    memoryThresholds: {
      warning: 512,   // 512MB
      critical: 1024, // 1GB
      maximum: 2048   // 2GB
    }
  }

  private status: OptimizationStatus = {
    isInitialized: false,
    isOptimizing: false,
    lastOptimizationTime: 0,
    optimizationCount: 0,
    errors: []
  }

  private performanceObserver?: PerformanceObserver
  private metrics: PerformanceMetrics = {
    pageLoadTime: 0,
    firstContentfulPaint: 0,
    largestContentfulPaint: 0,
    cumulativeLayoutShift: 0,
    firstInputDelay: 0,
    memoryUsage: 0,
    cacheHitRate: 0,
    renderTime: 0
  }

  // private _workspaceStore: any = null
  private _dumpStore: any = null

  // private get _workspaceStore_unused() {
  //   if (!this._workspaceStore) {
  //     this._workspaceStore = useWorkspaceStore()
  //   }
  //   return this._workspaceStore
  // }

  private get dumpStore() {
    if (!this._dumpStore) {
      this._dumpStore = useDumpStore()
    }
    return this._dumpStore
  }

  constructor(customConfig?: Partial<OptimizationConfig>) {
    if (customConfig) {
      this.config = { ...this.config, ...customConfig }
    }
  }

  /**
   * 初始化性能优化服务
   */
  async initialize(): Promise<void> {
    if (this.status.isInitialized) {
      console.log('[PerformanceOptimization] 服务已初始化')
      return
    }

    console.log('[PerformanceOptimization] 初始化性能优化服务')
    
    try {
      // 初始化性能监控
      this.initializePerformanceMonitoring()
      
      // 配置内存管理
      if (this.config.enableMemoryManagement) {
        memoryManagementService.setThresholds(this.config.memoryThresholds)
      }
      
      // 预热缓存
      if (this.config.cachePrewarmingEnabled) {
        await this.prewarmCaches()
      }
      
      this.status.isInitialized = true
      console.log('[PerformanceOptimization] 性能优化服务初始化完成')
      
    } catch (error) {
      const errorMsg = `初始化失败: ${error}`
      this.status.errors.push(errorMsg)
      console.error('[PerformanceOptimization]', errorMsg)
      throw error
    }
  }

  /**
   * 优化工作区性能
   */
  async optimizeWorkspace(workspaceId: string): Promise<void> {
    if (this.status.isOptimizing) {
      console.log('[PerformanceOptimization] 优化正在进行中')
      return
    }

    this.status.isOptimizing = true
    const startTime = performance.now()
    
    try {
      console.log(`[PerformanceOptimization] 开始优化工作区: ${workspaceId}`)
      
      // 阶段1: 预加载关键数据
      await this.preloadCriticalData(workspaceId)
      
      // 阶段2: 启动分阶段渲染
      await this.startPhaseRendering(workspaceId)
      
      // 阶段3: 后台数据预加载
      this.startBackgroundPreloading(workspaceId)
      
      // 阶段4: 优化内存使用
      await this.optimizeMemoryUsage()
      
      const duration = performance.now() - startTime
      this.status.lastOptimizationTime = Date.now()
      this.status.optimizationCount++
      
      console.log(`[PerformanceOptimization] 工作区优化完成，耗时: ${duration.toFixed(2)}ms`)
      
    } catch (error) {
      const errorMsg = `工作区优化失败: ${error}`
      this.status.errors.push(errorMsg)
      console.error('[PerformanceOptimization]', errorMsg)
      throw error
    } finally {
      this.status.isOptimizing = false
    }
  }

  /**
   * 预加载关键数据
   */
  private async preloadCriticalData(workspaceId: string): Promise<void> {
    if (!this.config.enablePreloading) return
    
    console.log(`[PerformanceOptimization] 预加载关键数据: ${workspaceId}`)
    
    try {
      // 并行加载关键数据
      const criticalTasks = [
        dataLoaderService.loadDirectoryStructure(workspaceId, LoadPriority.IMMEDIATE),
        dataLoaderService.loadComponentList(workspaceId, LoadPriority.IMMEDIATE),
        dataLoaderService.loadDumpFilePaths(workspaceId, LoadPriority.HIGH)
      ]
      
      await Promise.allSettled(criticalTasks)
      console.log(`[PerformanceOptimization] 关键数据预加载完成`)
      
    } catch (error) {
      console.error('[PerformanceOptimization] 关键数据预加载失败:', error)
    }
  }

  /**
   * 启动分阶段渲染
   */
  private async startPhaseRendering(workspaceId: string): Promise<void> {
    if (!this.config.enableLazyLoading) return
    
    console.log(`[PerformanceOptimization] 启动分阶段渲染: ${workspaceId}`)
    
    try {
      await renderOptimizationService.startPhaseRendering(workspaceId)
      console.log(`[PerformanceOptimization] 分阶段渲染启动完成`)
      
    } catch (error) {
      console.error('[PerformanceOptimization] 分阶段渲染失败:', error)
    }
  }

  /**
   * 启动后台预加载
   */
  private startBackgroundPreloading(workspaceId: string): void {
    if (!this.config.enablePreloading) return
    
    console.log(`[PerformanceOptimization] 启动后台预加载: ${workspaceId}`)
    
    // 异步执行，不阻塞主流程
    setTimeout(async () => {
      try {
        // 预加载转储数据
        const dumpTypes: ('framework' | 'operation' | 'app')[] = ['framework', 'operation', 'app']
        
        for (const dumpType of dumpTypes) {
          // 检查是否有包含的转储文件
          const includedPaths = this.dumpStore.getIncludedPaths(workspaceId, dumpType === 'app' ? 'debug' : dumpType)
          
          if (includedPaths.length > 0) {
            await dataLoaderService.preloadDumpData(workspaceId, dumpType)
            
            // 每种类型之间稍作延迟，避免阻塞
            await new Promise(resolve => setTimeout(resolve, 1000))
          }
        }
        
        console.log(`[PerformanceOptimization] 后台预加载完成: ${workspaceId}`)
        
      } catch (error) {
        console.error('[PerformanceOptimization] 后台预加载失败:', error)
      }
    }, 2000) // 延迟2秒开始，确保关键渲染完成
  }

  /**
   * 优化内存使用
   */
  private async optimizeMemoryUsage(): Promise<void> {
    if (!this.config.enableMemoryManagement) return
    
    try {
      const memoryStats = await memoryManagementService.checkMemoryUsage()
      
      // 如果内存使用超过警告阈值，执行清理
      if (memoryStats.totalUsed > this.config.memoryThresholds.warning) {
        console.log(`[PerformanceOptimization] 内存使用过高，执行清理: ${memoryStats.totalUsed}MB`)
        await memoryManagementService.performSmartCleanup()
      }
      
    } catch (error) {
      console.error('[PerformanceOptimization] 内存优化失败:', error)
    }
  }

  /**
   * 预热缓存
   */
  private async prewarmCaches(): Promise<void> {
    console.log('[PerformanceOptimization] 开始预热缓存')
    
    try {
      // 从持久化存储恢复缓存
      await Promise.allSettled([
        logDataCache.warmup(async () => ({})),
        dumpPathCache.warmup(async () => ({})),
        componentCache.warmup(async () => ({}))
      ])
      
      console.log('[PerformanceOptimization] 缓存预热完成')
      
    } catch (error) {
      console.error('[PerformanceOptimization] 缓存预热失败:', error)
    }
  }

  /**
   * 初始化性能监控
   */
  private initializePerformanceMonitoring(): void {
    try {
      // 监控Web Vitals指标
      if ('PerformanceObserver' in window) {
        this.performanceObserver = new PerformanceObserver((list) => {
          for (const entry of list.getEntries()) {
            this.processPerformanceEntry(entry)
          }
        })
        
        // 监控各种性能指标
        const entryTypes = ['paint', 'largest-contentful-paint', 'layout-shift', 'first-input']
        
        entryTypes.forEach(type => {
          try {
            this.performanceObserver!.observe({ entryTypes: [type] })
          } catch (error) {
            console.warn(`[PerformanceOptimization] 无法监控 ${type} 指标:`, error)
          }
        })
      }
      
      // 监控页面加载时间
      window.addEventListener('load', () => {
        setTimeout(() => {
          this.calculatePageLoadTime()
        }, 0)
      })
      
    } catch (error) {
      console.error('[PerformanceOptimization] 性能监控初始化失败:', error)
    }
  }

  /**
   * 处理性能条目
   */
  private processPerformanceEntry(entry: PerformanceEntry): void {
    switch (entry.entryType) {
      case 'paint':
        if (entry.name === 'first-contentful-paint') {
          this.metrics.firstContentfulPaint = entry.startTime
        }
        break
        
      case 'largest-contentful-paint':
        this.metrics.largestContentfulPaint = entry.startTime
        break
        
      case 'layout-shift':
        if (!(entry as any).hadRecentInput) {
          this.metrics.cumulativeLayoutShift += (entry as any).value
        }
        break
        
      case 'first-input':
        this.metrics.firstInputDelay = (entry as any).processingStart - entry.startTime
        break
    }
  }

  /**
   * 计算页面加载时间
   */
  private calculatePageLoadTime(): void {
    const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming
    if (navigation) {
      this.metrics.pageLoadTime = navigation.loadEventEnd - navigation.fetchStart
    }
  }

  /**
   * 获取性能指标
   */
  getPerformanceMetrics(): PerformanceMetrics {
    // 更新实时指标
    this.updateRealTimeMetrics()
    return { ...this.metrics }
  }

  /**
   * 更新实时指标
   */
  private updateRealTimeMetrics(): void {
    try {
      // 更新内存使用
      if ('memory' in performance) {
        const memory = (performance as any).memory
        this.metrics.memoryUsage = memory.usedJSHeapSize / (1024 * 1024) // MB
      }
      
      // 更新缓存命中率
      const cacheStats = [
        logDataCache.getStats(),
        dumpPathCache.getStats(),
        componentCache.getStats()
      ]
      
      // 计算平均缓存命中率
      const totalHitRate = cacheStats.reduce((sum, stat) => sum + stat.hitRate, 0)
      this.metrics.cacheHitRate = cacheStats.length > 0 ? totalHitRate / cacheStats.length : 0
      
    } catch (error) {
      console.error('[PerformanceOptimization] 更新实时指标失败:', error)
    }
  }

  /**
   * 获取优化建议
   */
  getOptimizationSuggestions(): string[] {
    const suggestions: string[] = []
    const metrics = this.getPerformanceMetrics()
    
    // 基于指标提供建议
    if (metrics.firstContentfulPaint > 2000) {
      suggestions.push('首次内容绘制时间较长，建议启用预加载和缓存')
    }
    
    if (metrics.largestContentfulPaint > 4000) {
      suggestions.push('最大内容绘制时间较长，建议优化图片和大型资源加载')
    }
    
    if (metrics.cumulativeLayoutShift > 0.1) {
      suggestions.push('布局偏移较大，建议为图片和动态内容设置固定尺寸')
    }
    
    if (metrics.memoryUsage > this.config.memoryThresholds.warning) {
      suggestions.push('内存使用较高，建议启用智能缓存清理')
    }
    
    if (metrics.cacheHitRate < 80) {
      suggestions.push('缓存命中率较低，建议调整缓存策略')
    }
    
    return suggestions
  }

  /**
   * 获取缓存统计信息
   */
  getCacheStats() {
    return {
      logData: logDataCache.getStats(),
      dumpPath: dumpPathCache.getStats(),
      component: componentCache.getStats(),
      dataLoader: dataLoaderService.getCacheStats()
    }
  }

  /**
   * 获取渲染统计信息
   */
  getRenderStats() {
    return renderOptimizationService.getRenderStats()
  }

  /**
   * 获取内存统计信息
   */
  async getMemoryStats() {
    return await memoryManagementService.getMemoryStats()
  }

  /**
   * 获取优化状态
   */
  getOptimizationStatus(): OptimizationStatus {
    return { ...this.status }
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<OptimizationConfig>): void {
    this.config = { ...this.config, ...newConfig }
    
    // 应用新配置
    if (newConfig.memoryThresholds) {
      memoryManagementService.setThresholds(newConfig.memoryThresholds)
    }
    
    console.log('[PerformanceOptimization] 配置已更新:', this.config)
  }

  /**
   * 获取当前配置
   */
  getConfig(): OptimizationConfig {
    return { ...this.config }
  }

  /**
   * 清理工作区缓存
   */
  clearWorkspaceCache(workspaceId: string): void {
    console.log(`[PerformanceOptimization] 清理工作区缓存: ${workspaceId}`)
    dataLoaderService.clearWorkspaceCache(workspaceId)
  }

  /**
   * 重置性能指标
   */
  resetMetrics(): void {
    this.metrics = {
      pageLoadTime: 0,
      firstContentfulPaint: 0,
      largestContentfulPaint: 0,
      cumulativeLayoutShift: 0,
      firstInputDelay: 0,
      memoryUsage: 0,
      cacheHitRate: 0,
      renderTime: 0
    }
    console.log('[PerformanceOptimization] 性能指标已重置')
  }

  /**
   * 生成性能报告
   */
  generatePerformanceReport(): {
    metrics: PerformanceMetrics
    cacheStats: any
    memoryStats: any
    renderStats: any
    suggestions: string[]
    status: OptimizationStatus
  } {
    return {
      metrics: this.getPerformanceMetrics(),
      cacheStats: this.getCacheStats(),
      memoryStats: null, // 需要异步获取
      renderStats: this.getRenderStats(),
      suggestions: this.getOptimizationSuggestions(),
      status: this.getOptimizationStatus()
    }
  }

  /**
   * 销毁服务
   */
  destroy(): void {
    // 停止性能监控
    if (this.performanceObserver) {
      this.performanceObserver.disconnect()
    }
    
    // 销毁子服务
    renderOptimizationService.destroy()
    memoryManagementService.destroy()
    
    // 重置状态
    this.status.isInitialized = false
    this.status.isOptimizing = false
    
    console.log('[PerformanceOptimization] 性能优化服务已销毁')
  }
}

// 全局性能优化服务实例
export const performanceOptimizationService = new PerformanceOptimizationService()